package com.lanou3g.springmvc.web;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

/**
 * 使用apache fileupload实现文件上传
 */
@Controller
@RequestMapping("/commons")
public class CommonsFileUploadController {

    @RequestMapping("/upload")
    public String upload(@RequestParam("myFile") MultipartFile file, HttpServletRequest req, Model model) {
        try {
            file.transferTo(new File(WebUtils.getRealPath(req.getServletContext(), "/upload/")+file.getOriginalFilename()));
        } catch (IOException e) {
            e.printStackTrace();
        }

        StringBuilder sb = new StringBuilder();
        sb.append("http://localhost:8080/upload/");
        sb.append(file.getOriginalFilename());

        model.addAttribute("filePath", sb.toString());
        model.addAttribute("fileName", file.getOriginalFilename());

        return "filelist";
    }



}
